<template>
    <div class="article-edit">
        <el-card class="!border-none" shadow="never">
            <el-page-header :content="$route.query.type == 'pass'?'服务商审核':$route.meta.title" @back="$router.back()" />
        </el-card>
        <el-tabs class="align-middle" v-model="defaultTab">
            <el-form ref="formRef" :model="formData" :rules="rules">
                <el-tab-pane label="基本信息" name="channel_info">

                    <el-card class="!border-none mt-4" shadow="never">
                        <div class="font-medium mb-7">基础信息</div>
                        <el-form-item label="姓名" prop="name">
                            <div class="w-80">
                                <el-input v-model="formData.name" placeholder="请输入姓名" type="text" maxlength="15"
                                    show-word-limit clearable />
                            </div>
                        </el-form-item>

                        <el-form-item label="头像" prop="header">
                            <div class="w-80">
                                <div>
                                    <material-picker v-model="formData.header" :limit="1" />
                                </div>
                                <div class="form-tips">建议尺寸：200*200px</div>
                            </div>
                        </el-form-item>

                        <el-form-item label="个人简介" prop="desc">
                            <div class="w-80">
                                <el-input v-model="formData.desc" placeholder="请输入个人简介" type="textarea"
                                    :autosize="{ minRows: 2, maxRows: 6 }" maxlength="600" show-word-limit clearable />
                            </div>
                        </el-form-item>

                        <el-form-item label="微信号" prop="wx_no">
                            <div class="w-80">
                                <el-input v-model="formData.wx_no" placeholder="请输入微信号" type="text" maxlength="30"
                                    show-word-limit clearable />
                            </div>
                        </el-form-item>

                        <el-form-item label="身份证号" prop="id_card">
                            <div class="w-80">
                                <el-input v-model="formData.id_card" placeholder="请输入身份证号" type="text"
                                    maxlength="18" show-word-limit clearable />
                            </div>
                        </el-form-item>

                        <el-form-item label="手机号" prop="phone">
                            <div class="w-80">
                                <el-input v-model="formData.phone" placeholder="请输入手机号" type="text" maxlength="11" :disabled="!!route.query.id"
                                    show-word-limit clearable />
                            </div>
                        </el-form-item>
                        <el-form-item v-if="route.query.id" label="提交人手机号" prop="user_phone">
                            <div class="w-80">
                                <el-input v-model="formData.user_phone" placeholder="请输入手机号" type="text" maxlength="11" :disabled="!!route.query.id"
                                    show-word-limit clearable />
                            </div>
                        </el-form-item>

                        <el-form-item label="公司" prop="company">
                            <div class="w-80">
                                <el-input v-model="formData.company" placeholder="请输入公司名称" type="text"
                                    maxlength="50" show-word-limit clearable />
                            </div>
                        </el-form-item>

                        <el-form-item label="已认证" prop="is_auth">
                            <div class="w-80">
                                <el-radio-group v-model="formData.is_auth">
                                    <!-- works when >=2.6.0, recommended ✔️ not work when <2.6.0 ❌ -->
                                    <!--              <el-radio value="Value 1">Option 1</el-radio>-->
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="0">否</el-radio>
                                </el-radio-group>
                            </div>
                        </el-form-item>


                        <el-form-item label="地址" prop="address">
                            <div class="w-80">
                                <el-input v-model="formData.address" placeholder="请输入地址" type="text"
                                    maxlength="100" show-word-limit clearable  />
                                    <!-- @focus="focusAddress" -->
                                    <el-button @click="focusAddress">地图选点</el-button>
                            </div>
                        </el-form-item>

                        <el-form-item label="经度" prop="lon">
                            <div class="w-80">
                                <el-input v-model="formData.lon" placeholder="请输入经度" type="text" maxlength="30"
                                    show-word-limit clearable />
                            </div>
                        </el-form-item>

                        <el-form-item label="纬度" prop="lat">
                            <div class="w-80">
                                <el-input v-model="formData.lat" placeholder="请输入纬度" type="text" maxlength="30"
                                    show-word-limit clearable />
                            </div>
                        </el-form-item>

                        <el-form-item label="职务" prop="position_name">
                            <div class="w-80">
                                <el-input v-model="formData.position_name" placeholder="请输入职务" type="text" maxlength="10"
                                    show-word-limit clearable />
                            </div>
                        </el-form-item>

                        <el-form-item label="服务类型" prop="cate_id">
                            <div class="w-80">
                                <el-select class="w-[280px]" multiple :multiple-limit="3" v-model="formData.cate_id" @change="changeProductCate">
                                    <el-option v-for="(item) in cate_list" :label="item.name"
                                        :value="String(item.id)" :key="String(item.id)" />
                                </el-select>
                            </div>
                        </el-form-item>

                        <el-form-item label="标签" prop="tag_ids">
                            <div style="width: 60%;">
                                <el-checkbox-group v-model="formData.tags" :max="3">
                                    <el-checkbox v-for="item in optionsData.tag_list" :label="item.name.toString()"
                                        :value="item.name.toString()" :key="item.name.toString()">
                                        {{ item.name }}
                                    </el-checkbox>
                                </el-checkbox-group>
                            </div>
                        </el-form-item>
                        <!-- <el-form-item label="" prop="tag_ids">
                            <div>
                                <el-button :icon="Plus" @click="open">新增标签</el-button>
                            </div>
                        </el-form-item> -->
                       

                        <el-form-item label="启用状态" prop="is_enable">
                            <div class="w-80">
                                <!-- :disabled="!route.query.id" -->
                                <el-radio-group v-model="formData.is_enable">
                                    <!-- works when >=2.6.0, recommended ✔️ not work when <2.6.0 ❌ -->
                                    <!--              <el-radio value="Value 1">Option 1</el-radio>-->
                                    <el-radio :label="1">启用</el-radio>
                                    <el-radio :label="0">停用</el-radio>
                                </el-radio-group>
                            </div>
                        </el-form-item>


                    </el-card>
                </el-tab-pane>
                <el-tab-pane label="服务产品" name="relate_product">
                    <editor v-if="defaultTab == 'relate_product'" v-model="formData.infos" :height="567" />
                </el-tab-pane>
            </el-form>
        </el-tabs>
        <footer-btns>
            <el-button v-if="$route.query.type != 'pass'" type="primary" @click="handleSave" v-prevent-reclick="3000">保存</el-button>
            <el-button v-if="$route.query.type == 'pass'" type="primary" @click="handleSave" v-prevent-reclick="3000">审核通过</el-button>
            <el-button v-if="$route.query.type == 'pass'"  @click="()=>{$router.back()}">取消</el-button>
        </footer-btns>

        <product-popup v-if="showProduct" ref="productRef" @success="getProduct" @close="showProduct = false" />
        <map-area ref="mapArea" @save="mapInfo" />
    </div>
</template>

<script lang="ts" setup name="channelListsEdit">
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { saveUser, userInfo, serviceTag, cateList, passUser, getDetail, passDetail } from '@/api/service';
import useMultipleTabs from '@/hooks/useMultipleTabs'
import { useDictOptions } from "@/hooks/useDictOptions";
import feedback from '@/utils/feedback';
import ProductPopup from './producet.vue';
import MapArea from '@/components/map/index.vue'
// import MapArea from '@/components/map/other.vue'
import { shallowRef, ref, nextTick, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
const productRef = shallowRef<InstanceType<typeof ProductPopup>>()
const mapArea = ref()
const showProduct = ref(false)
// 子组件成功回调
const getProduct = (val:any)=>{
	console.log(val);
}
// 点击添加产品按钮，打开弹窗
const productAdd = async () => {
    console.log('点击添加产品')
    showProduct.value = true
	await nextTick()
	productRef.value?.open('add')
}

//点击选择地址
const focusAddress = (e: any) => {
    console.log(e)
    console.log('focus')
    mapArea.value.keywords(formData.address);
    mapArea.value.dialogVisible(true);
}

// 地图信息返回
const mapInfo = async (data: any) => {
    console.log(data)
    formData.address = data.name;
    formData.lon = data.location.lng;
    formData.lat = data.location.lat;
}

const tableData = [
  {
    id:1,
    date: '2016-05-03',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  }]

const route = useRoute()
const router = useRouter()
const formData = reactive({
    id: '',
    name: '',
    header: '',
    desc: '',
    wx_no: '',
    id_card: '',
    phone: '',
    user_phone: '',
    company: '',
    address: '',
    position_name: '',
    cate_id: [],
    tag_ids: [],
    tags: [],
    is_enable: 1,
    is_auth: '',
    infos: '',
    lon: '',
    lat: ''
})

const { removeTab } = useMultipleTabs()
const formRef = shallowRef<FormInstance>()
const rules = reactive({
    name: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
    header: [{ required: true, message: '请选择头像', trigger: 'blur' }],
    id_card: [{ required: true, message: '请填写身份证号', trigger: 'blur' }],
    phone: [{ required: true, message: '请填写手机号', trigger: 'blur' }],
    company: [{ required: true, message: '请填写公司名称', trigger: 'blur' }],
    address: [{ required: true, message: '请填写公司地址', trigger: 'blur' }],
    lon: [{ required: true, message: '请填写经度', trigger: 'blur' }],
    lat: [{ required: true, message: '请填写纬度', trigger: 'blur' }],
    position_name: [{ required: true, message: '请填写职位', trigger: 'blur' }],
    cate_id: [{ required: true, message: '请选择服务类型', trigger: 'blur' }],
    is_enable: [{ required: true, message: '请选择启用状态', trigger: 'blur' }],
    is_auth: [{ required: true, message: '请选择是否认证', trigger: 'blur' }],
})
//默认选择的tab
const defaultTab = ref('channel_info')

const open = () => {
  ElMessageBox.prompt('请输入新的标签', '新增标签', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
    .then(({ value }) => {
    optionsData.tag_list.push({
        name: value
    })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Input canceled',
      })
    })
}

// 获取当前详情
const getDetails = async () => {
    await nextTick()
    const data = await userInfo({
        id: route.query.id
    })
    data.tag_ids = [];
    let arr: number[] = []
    data.cate_id.split(',').forEach((item: any)=>{
        if (item !== '') {
            arr.push(item)
        }
    })
    data.cate_id = arr
    Object.keys(formData).forEach((key) => {
        //@ts-ignore
        formData[key] = data[key]
    })
    console.log(data.cate_id)
    console.log(formData)
    await nextTick()
    setTimeout(()=>{
        let objArr:any = []
        optionsData.tag_list.forEach((itemC)=>{
            objArr.push(itemC.name)
        })
        console.log('tag_list')
        console.log(objArr)
        if (data.tags.length == 0) {
            return false
        }
        data.tags.forEach((item: any)=>{
            console.log(item)
            if (objArr.indexOf(item) === -1) {
                console.log('no'+item)
                optionsData.tag_list.push({
                    name: item
                })
            }
        })
        console.log( optionsData.tag_list)
    },300)
    
}

const { optionsData } = useDictOptions<{
    // cateList: any,
    tag_list: any[]
}>({
    // cateList: {
    //     api: cateList
    // },
    tag_list: {
        api: serviceTag
    }
})
console.log(optionsData)

const cate_list:any = ref([])
const getCateList = async () => {
    const res = await cateList({})
    console.log(res)
    let arr:any = []
    res.lists.forEach(((item:any)=>{
        if (item.is_enable == 1) {
           arr.push(item)
        }
    }))
    cate_list.value = arr;
}
getCateList()

const handleSave = async () => {
    await formRef.value?.validate()
    let params = JSON.parse(JSON.stringify(formData));
    console.log(params)
    params.cate_id = params.cate_id.join(',')
    params.tags = params.tags.join(',')
    if (route.query.type == 'pass') {
        await feedback.confirm('确认审核通过？')
        await saveUser(params)
        if (route.query.status == '4') {
            await passDetail({ id: params.id })
        } else {
            await passUser({ id: params.id })
        }
        feedback.msgSuccess('审核通过')
    } else if (route.query.id) {
        await saveUser(params)
        feedback.msgSuccess('保存成功')
    } else {
        await saveUser(params)
        feedback.msgSuccess('新增成功')
    }
    removeTab()
    router.back()

}
// 主营业务选中数据发生变化
const changeProductCate = (val: any) => {
    console.log(val)
}

// 获取当前详情
const getDetailNew = async () => {
    await nextTick()
    const data = await getDetail({
        id: route.query.id
    })
    data.tag_ids = [];
    let arr: number[] = []
    data.cate_id.split(',').forEach((item: any)=>{
        if (item !== '') {
            arr.push(item)
        }
    })
    data.cate_id = arr
    formData.is_auth = '0'
    formData.is_enable = 1
    Object.keys(formData).forEach((key) => {
        //@ts-ignore
        formData[key] = data[key]
    })
    console.log(data.cate_id)
    console.log(formData)
    await nextTick()
    setTimeout(()=>{
        let objArr:any = []
        optionsData.tag_list.forEach((itemC)=>{
            objArr.push(itemC.name)
        })
        console.log('tag_list')
        console.log(objArr)
        if (data.tags.length == 0) {
            return false
        }
        data.tags.forEach((item: any)=>{
            console.log(item)
            if (objArr.indexOf(item) === -1) {
                console.log('no'+item)
                optionsData.tag_list.push({
                    name: item
                })
            }
        })
        console.log( optionsData.tag_list)
    },300)
    
}
// if (route.query.status == '4') {
//     route.query.id &&  getDetailNew()
// } else {
//     route.query.id && getDetails()
// }
route.query.id &&  getDetailNew()
</script>
<style scoped lang="scss">
::v-deep .el-tabs__nav-wrap {
    overflow-x: auto;
    width: 86%;
    margin-left: 10px;
}

::v-deep .el-tabs__nav-wrap::after {
    display: none;
}
</style>